import hashlib
from typing import Dict, Any

from fastapi import Request
from user_agents import parse

from app.schemas.base_schema import DeviceType


def get_device_info(request: Request) -> Dict[str, Any]:
    """获取客户端设备信息"""
    user_agent = request.headers.get("user-agent", "")
    ip_address = request.client.host if request.client else "unknown"
    ua = parse(user_agent)

    # 生成设备指纹
    accept_language = request.headers.get("accept-language", "")
    fingerprint_str = f"{ip_address}|{user_agent}|{accept_language}"
    device_fingerprint = hashlib.sha256(fingerprint_str.encode()).hexdigest()

    device_type = get_device_type(ua)
    os = f"{ua.os.family} {ua.os.version_string}".strip()
    browser = f"{ua.browser.family} {ua.browser.version_string}".strip()
    name = f"{device_type}-{os}"
    return {
        "os": os,
        "browser": browser,
        "name":name,
        "ip_address": ip_address,
        "user_agent": user_agent,
        "type": device_type,
        "device_fingerprint": device_fingerprint,
    }


def get_device_type(ua) -> DeviceType:
    """获取设备类型"""
    if ua.is_mobile:
        device_type = DeviceType.mobile
    elif ua.is_tablet:
        device_type = DeviceType.tablet
    elif ua.is_pc:
        device_type=DeviceType.pc
    elif ua.is_bot:
        device_type = DeviceType.bot
    else:
        device_type = DeviceType.other
    return device_type
